package oop.ex1.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//###############
//FILE : DiskAttributesFilter.java
//WRITER : Amir Wilf, wilfoa, 300007085
//WRITER : Daniel Acherkan, danithelion, 310116348
//EXERCISE : oop ex1 2011
//DESCRIPTION:
//A action which copies a file to a different location.
//###############

public class CopyAction extends DirectoryAction implements Action{
	//constants
	private static final String SLASH = System.getProperty("file.separator");
	
	//constructor
	public CopyAction(String source, String target) {
		super(source, target);
	}

	/**
	 * Copies a file to a new location
	 * @param file the file to be copied. 
	 */
	public void doAction(File file) throws IOException{
		String[] fileName;
		//will be used for reading flag from the file
		int result;
		//making sure the source path is actually a directory
		if(!validatePath(this._source)){
			throw new IOException();
		}
		//getting the full path for the copy
		String fullTarget = adjustPath();
		//getting the file name itself apart for the path
		fileName = file.getCanonicalPath().split(SLASH);
		fullTarget += fileName[fileName.length-1];
		InputStream input = null;
		OutputStream output = null;
		try{
			input = new FileInputStream(file.getCanonicalPath());
			output = new FileOutputStream(fullTarget);			
			while((result = input.read()) != -1){
				output.write(result);
			}
		}catch(IOException ioErrorHandler){
			System.exit(-1);
		}finally{
			try{
				if(input != null){
					input.close();
				}
				if(output != null){
					output.close();
				}
			}catch(IOException e){
				throw new IOException();
			}
		}
	}

	
	//A private method which returns the full path of the target location
	//to which the file is copied.
	private String adjustPath() {
		String result = "";
		//adjusting the target path in order to rightly concatenate it
		String[] directories = this._target.split(SLASH);
		if(!(this._source.charAt(this._source.length()-1) == SLASH.charAt(0))){
			this._source += SLASH;
		}
		result += this._source;
		//if the path is compiled from several paths - create each directory
		for(String directory : directories){
			result += directory  +SLASH;
			//if the path doesn't exist - create it
			if(!validatePath(result)){
				new File(result).mkdir();
			}
		}
		return result;
		
	}

	//returns true if a given path is of a directory, and false otherwise.
	private static boolean validatePath(String source) {
		File file = new File(source);
		return(file.isDirectory());
	}
}
